package com.itheima.factory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Date;
import java.util.ResourceBundle;

public class BeanFactory {

    public static Object getBean(String name) {

        try {
            ResourceBundle beans = ResourceBundle.getBundle("beans");
            String className = beans.getString(name);
            Class clazz = Class.forName(className);
            Object object = clazz.newInstance();

            InvocationHandler invocationHandler = new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    Object invoke = null;
                //需求：在不修改现有代码的基础上，添加日志代码，记录所有`业务层`方法的执行时刻和信息
                // （包括类名、方法名、入参、异常信息等等）
                    StringBuilder builder = new StringBuilder();
                    builder.append("时间:").append(new Date());
                    builder.append("类名:").append(object.getClass().getSimpleName());
                    builder.append("方法名:").append(method.getName());
                    builder.append("参数:").append(Arrays.toString(args));
                    try {
                        invoke = method.invoke(object, args);
                    } catch (Exception ex) {
                        builder.append("异常信息:").append(ex.getMessage());
                        throw ex;
                    }
                    System.out.println(builder);
                    return invoke;
                }
            };
            //动态代理增强,实现日志功能
            Object proObject = Proxy.newProxyInstance(object.getClass().getClassLoader(),
                    object.getClass().getInterfaces(),
                    invocationHandler);
            return proObject;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
